//
//  NSMutableAttributedString+Safe.m
//  CommonTool
//
//  Created by Name i on 2022/4/14.
//

#import "NSMutableAttributedString+Safe.h"

@implementation NSMutableAttributedString (Safe)

+ (void)exchangeMethod {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        Class concreteMutableAttributedString = NSClassFromString(@"NSConcreteMutableAttributedString");
        
        //initWithString:
        [NSObject tnSwizzlingInstanceMethod:@selector(initWithString:)
                                 withMethod:@selector(safe_initWithString:)
                                  withClass:concreteMutableAttributedString];
        
        //initWithString:attributes:
        [NSObject tnSwizzlingInstanceMethod:@selector(initWithString:attributes:)
                                 withMethod:@selector(safe_initWithString:attributes:)
                                  withClass:concreteMutableAttributedString];
    });
}

- (instancetype)safe_initWithString:(NSString *)str {
    id object = nil;
    @try {
        object = [self safe_initWithString:str];
    }
    @catch (NSException *exception) {
        [NNDefender crashWithException:exception defaultToDo:NNDefenderDefaultReturnNil];
    }
    @finally {
        return object;
    }
}


- (instancetype)safe_initWithString:(NSString *)str attributes:(NSDictionary<NSAttributedStringKey,id> *)attrs {
    id object = nil;
    @try {
        object = [self safe_initWithString:str attributes:attrs];
    }
    @catch (NSException *exception) {
        [NNDefender crashWithException:exception defaultToDo:NNDefenderDefaultReturnNil];
    }
    @finally {
        return object;
    }
}


@end
